require "Global"
require "Array"
require "ActionUtil"
require "TimeManager"
require "UITimer"
require "ItemManager"
require "XunZhangManager"
require "Decorate"
require "Technology"
require "Dialog"
require "Quest"
require "General"
require "Player"
require "Battle"
require "CheckBox"
require "JiaSuDialog"
require "JiaSuSampleDialog"
require "LoadScene"
require "WarResultScene"
require "WarScene"
require "ZhuangBeiScene"
require "ZhanFuYingScene"
require "ZhuangBeiLayer3"
require "ZBQHLayer"
require "ZBCDLayer"
require "ZBHCLayer"
require "BSHCLayer"
require "JunXiaoLayer0"
require "DailyRewardScene"
require "ZhanDouScene"
require "KeXueYuanScene"
require "XunLianYingScene"
require "ZhiHuiBuScene"
require "RenWuScene"
require "RenWuDailyScene"
require "JunXiaoScene"
require "JunYingScene"
require "YinHangScene"
require "JingJiChangScene"
require "YuanZhenScene"
require "YuanZhenShopScene"
require "JiuGuanScene"
require "ShouXunScene"
require "ShouXunScene1"
require "FriendScene"
require "ShopScene"
require "ShopScene1"
require "BeginScene"
require "SelectNameScene"
require "AddPowerCashScene"
--require "UpgradeManager"
require "JunXiaoGuide"
require "ZhiHuiBuGuide"
require "RenWuGuide"
require "ZhuangBeiGuide"
require "XunLianYingGuide"
require "KeXueYuanGuide"

MainScene={}
local NodeID = {ScrollView=101, ZhiHuiBu=1001, JunXiao=1002, KeXueYuan=1003, ZhanFuYing=1004, XunLianYing=1005, JinJiChang=1008,
                HeadBK=10001, ZhanDouLiLabel=10002, JunXiangLabel=10003, CashLabel=10004, SoldierLabel=10005, LevelLabel=10006,
                ExpLabel=10007, TiLiLabel=10008, ExpBarBK=10009}
MainScene.expBar = nil
MainScene.expText = nil

MainScene.getNode = function()
  local b = usecond() 
  MainScene.node = CCBReader:load("Main.ccbi")
  MainScene.mainui = CCBReader:load("MainUI.ccbi")
  print("MainScene.onLoadTimer", MainScene.node, MainScene.mainui)
  local e1 = usecond() 
  MainScene.init()
  local e2 = usecond()
  print("MainScene.getNode cost", e2-e1, e1-b)
  MainScene.timerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(MainScene.onTimer, 0.5, false)  
  --MainScene.loadTimerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(MainScene.onLoadTimer, 0.01, false)  
  return MainScene.node
end

MainScene.getScene = function()
  MainScene.node = nil
  local sc = CCScene:create()
  sc:addChild(MainScene.getNode())
  print("WarScene.getScene", sc)
  MainScene.scene = sc
  --sc:retain()
  return sc  
end

MainScene.loadMainScene = function()
  print("MainScene.loadMainScene")
  --MainScene.timerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(MainScene.onTimer, 0.5, false)
  MainScene.loadTimerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(MainScene.onLoadTimer, 0.01, false)
end

MainScene.onTimer = function()
  --MainScene.checkLoginReward()
  CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(MainScene.timerID)
end
MainScene.onLoadTimer = function()
  if MainScene.loadState==nil then MainScene.loadState=1 end
  if MainScene.loadState==1 then
    MainScene.node = CCBReader:load("Main.ccbi")
    MainScene.mainui = CCBReader:load("MainUI.ccbi")
    print("MainScene.onLoadTimer", MainScene.node, MainScene.mainui)
    MainScene.node:addChild(MainScene.mainui) 
    MainScene.loadState = 2
  elseif MainScene.loadState==2 then 
    BeginScene.instance:showProgress(70)
    MainScene.init()
    MainScene.loadState = 3
  elseif MainScene.loadState==3 then 
    BeginScene.instance:showProgress(100)  
    local sc = CCScene:create()
    sc:addChild(MainScene.node)
    MainScene.scene = sc 
    CCDirector:sharedDirector():replaceScene(sc)
    CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(MainScene.loadTimerID)
    MainScene.timerID = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(MainScene.onTimer, 0.5, false)
  end
end

MainScene.checkDailyRenWuComplete = function()
  local flag = false
  local quests = UserData.userinfo.host.current.d
  for k,v in pairs(quests) do
    local quest = Quest:create(tonumber(k))
    if quest:checkComplete()==true then
      flag = true
      break
    end
  end
  return flag
end
MainScene.checkRenWuComplete = function()
  local flag = false
  for k,v in pairs(UserData.userinfo.curQuests) do
    print("MainScene.checkRenWuComplete", v)
    if v>0 then
      local q = Quest:create(v)
      if q:checkComplete()==true then
        flag = true
        break
      end
    end
  end
  for k,v in pairs(UserData.userinfo.host.currentQuests) do
    local quest = Quest:create(tonumber(k)) 
    if quest.info.type == "bounty" then
      if quest:checkComplete()==true then
        flag = true
        break
      end
    end
  end
  return flag
end
MainScene.getBuildingName = function(idStr)
  local buildings = Array:create(UserData.config.models.Building2)
  print("MainScene.getBuildingName", UserData.config.models.Building2)
  for i=0,buildings:size()-1 do
    if tonumber(idStr)==buildings:at(i).id then
      return buildings:at(i).name
    end
  end
end

MainScene.setBuildingLevel = function(idStr)
  local text = string.format("%s Lv%d", MainScene.getBuildingName(idStr), UserData.userinfo.host.cities2[idStr].l)  
  local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  local l = scroll:getChildByTag(1)
  if l~=nil then
    local lb = l:getChildByTag(1)
    TypeCast(lb, "CCLabelTTF"):setString(text)
  else
    local jz = MainScene.getBuilding(tonumber(idStr))
    if jz:isVisible()==false then
      return
    end
    l = CCLayer:create()
    bk = CCSprite:create("bk0009.png")
    bk:setScaleX(0.3)
    bk:setScaleY(0.1)
    l:addChild(bk)
  
    print("MainScene.setBuildingLevel", idStr)
    local lb = CCLabelTTF:create(text, "Arial", 18)
    local x,y = jz:getPosition()
    lb:setTag(1)
    --local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
    l:addChild(lb)
    l:setTag(1)
    l:setPosition(x-10,y-60)
    scroll:addChild(l)
  end
end

MainScene.initBuildingLevelLabel = function()
  local curBuildings = UserData.userinfo.host.cities2
  for k,v in pairs(curBuildings) do
    if tonumber(k)<2000 then
      print("MainScene.initBuildingLevelLabel", k)
      MainScene.setBuildingLevel(k)
    end 
  end
end

MainScene.setState = function()
  if MainScene.maskSp~=nil then
    local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
    scroll = TypeCast(scroll, "CCScrollView")
    local cl = scroll:getContainer()
    cl:removeChild(MainScene.maskSp, true)
    MainScene.maskSp = nil
  end
  MainScene.setBuildingVisible()
  
  local bk = MainScene.mainui:getChildByTag(NodeID.HeadBK) 
  bk = TypeCast(bk, "CCSprite")
  print("visible", bk:isVisible(), bk:getZOrder(), bk:getTexture())
  local lb = MainScene.mainui:getChildByTag(NodeID.SoldierLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d", UserData.userinfo.host.soldiers))
  local bl = UserData.userinfo.host.cities2[tostring(BuildingID.JunYing)].l
  local binfo = UserData.config.models[BuildingLevel[BuildingID.JunYing]][bl]
  if UserData.userinfo.host.soldiers >= binfo.soldierMax then
    TypeCast(lb, "CCLabelTTF"):setColor(ccc3(255,0,0))
  else
    TypeCast(lb, "CCLabelTTF"):setColor(ccc3(255,255,255))
  end
  
  lb = MainScene.mainui:getChildByTag(NodeID.CashLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d", UserData.userinfo.host.cash))
  bl = UserData.userinfo.host.cities2[tostring(BuildingID.YinHang)].l
  binfo = UserData.config.models[BuildingLevel[BuildingID.YinHang]][bl]
  if UserData.userinfo.host.cash >= binfo.cashUpLimit then
    TypeCast(lb, "CCLabelTTF"):setColor(ccc3(255,0,0))
  else
    TypeCast(lb, "CCLabelTTF"):setColor(ccc3(255,255,255))
  end
  lb = MainScene.mainui:getChildByTag(NodeID.LevelLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d", UserData.userinfo.host.level))
  lb = MainScene.mainui:getChildByTag(NodeID.ZhanDouLiLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d", UserData.userinfo.host.fightingPower))
  lb = MainScene.mainui:getChildByTag(NodeID.JunXiangLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d", UserData.userinfo.host.coin))
  lb = MainScene.mainui:getChildByTag(NodeID.TiLiLabel)
  TypeCast(lb, "CCLabelTTF"):setString(string.format("%d/120", UserData.userinfo.host.power))

  local needXP = UserData.config.models.RankLevel[UserData.userinfo.host.level].threshold
  local curXP = UserData.userinfo.host.xp
  local xpbarbk = MainScene.mainui:getChildByTag(NodeID.ExpBarBK)
  local x,y = xpbarbk:getPosition()
  if MainScene.expBar==nil then 
    local xpsp = CCSprite:create("523.png")
    local xpbar = CCProgressTimer:create(xpsp)
    xpbar:setType(kCCProgressTimerTypeBar)
    xpbar:setMidpoint(ccp(0,0))
    xpbar:setBarChangeRate(ccp(1, 0))
    xpbar:setPosition(x,y)
    xpbarbk:getParent():addChild(xpbar)

    local lb = CCLabelTTF:create(string.format("%d/%d", curXP, needXP), "Helvetica", 18)
    lb:setPosition(x,y)
    xpbarbk:getParent():addChild(lb)
    MainScene.expText = lb
    MainScene.expBar = xpbar
  end
  MainScene.expBar:setPercentage(curXP/needXP*100.0)
  MainScene.expText:setString(string.format("%d/%d", curXP, needXP))

  if MainScene.renwuStateSp==nil then
    MainScene.renwuStateSp = CCSprite:create("renwu_doing.png") 
    MainScene.renwuStateSp:setPosition(ccp(100, 380))
    MainScene.mainui:addChild(MainScene.renwuStateSp)
  end
  
  if MainScene.checkRenWuComplete()==true then
    MainScene.renwuStateSp = setSpriteImg(MainScene.renwuStateSp, "renwu_done.png") 
  else
    MainScene.renwuStateSp = setSpriteImg(MainScene.renwuStateSp, "renwu_doing.png")
  end
  local ac1 = CCScaleTo:create(0.2, 1.2)
  local ac2 = CCScaleTo:create(0.2, 1)
  local ac3 = CCDelayTime:create(1) 
  local sac = ActionUtil.createSeqAction({ac1, ac2, ac3})
  sac = TypeCast(sac, "CCActionInterval")
  MainScene.renwuStateSp:runAction(CCRepeatForever:create(sac))

  if MainScene.checkDailyRenWuComplete()==true then
    if MainScene.renwuDailyStateSp==nil then
      MainScene.renwuDailyStateSp = CCSprite:create("renwu_done.png") 
      MainScene.renwuDailyStateSp:setPosition(ccp(100, 280))
      MainScene.mainui:addChild(MainScene.renwuDailyStateSp)
    end
    local ac1 = CCScaleTo:create(0.2, 1.2)
    local ac2 = CCScaleTo:create(0.2, 1)
    local ac3 = CCDelayTime:create(1)
    local sac = ActionUtil.createSeqAction({ac1, ac2, ac3})
    sac = TypeCast(sac, "CCActionInterval")
    MainScene.renwuDailyStateSp:runAction(CCRepeatForever:create(sac)) 
  else
    if MainScene.renwuDailyStateSp~=nil then
      MainScene.renwuDailyStateSp:getParent():removeChild(MainScene.renwuDailyStateSp, true)
      MainScene.renwuDailyStateSp = nil
    end
  end
end
MainScene.addMask = function(id)
  local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  scroll = TypeCast(scroll, "CCScrollView")
  scroll:setContentOffset(ccp(-50, -200)) 
  
  local cl = scroll:getContainer()
  local img = string.format("bmask%d.png", id)
  local sp = CCSprite:create(img)
  sp:setPosition(1242/2, 856/2)
  cl:addChild(sp)
  MainScene.maskSp = sp
 
  setTouchEnabledAll(MainScene.node, false)
  setTouchEnabledAll(scroll:getContainer():getChildByTag(id), true) 
  --return scroll:getContainer():getChildByTag(id)
end
MainScene.getBuilding = function(id)
  local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  scroll = TypeCast(scroll, "CCScrollView")
  return scroll:getContainer():getChildByTag(id)
end

MainScene.addBuildAction = function(id, name, prefix, dur)
  if dur==nil then dur=0.2 end
  local ac = ActionUtil.createAction(name, dur, prefix)
  print("MainScene.addBuildAction", id)
  local jz = MainScene.getBuilding(id)
  if jz:isVisible()==false then
    return
  end
  local cs = jz:getChildren()
  print("MainScene.addBuildAction", cs:count())
  --for i=0, cs:count()-1 do
  --  print("@@@", TypeCast(cs:objectAtIndex(i), "CCNode"):getTag())
  --end
  local sp = CCSprite:createWithSpriteFrameName(string.format("%s_1.png", prefix))
  sp:setPosition(jz:getChildByTag(10001):getPosition())
  jz:addChild(sp)
  sp:runAction(CCRepeatForever:create(ac))
end
MainScene.checkLoginReward = function()
  if UserData.userinfo.host.cLoginRewards~=nil and #UserData.userinfo.host.cLoginRewards>0 then
    setTouchEnabledAll(MainScene.node, false) 
    MainScene.scene:addChild(DailyRewardScene.getNode().node)
  end
end
MainScene.init = function()

  --MainScene.checkLoginReward()
  --SimpleAudioEngine:sharedEngine():playBackgroundMusic("main.mp3",true)
  --SimpleAudioEngine:sharedEngine():setEffectsVolume(0.6)
  --SimpleAudioEngine:sharedEngine():setBackgroundMusicVolume(0.3)

  local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  scroll = TypeCast(scroll, "CCScrollView")
  scroll:setContentOffset(ccp(-50, -200)) 
  --print("###1") 
  --print("###2")
  addSpriteFromBK(MainScene.mainui, 1030, nameFromPath(UserData.userinfo.host.headpic))
  local lb = addLabelFromBK(MainScene.mainui, 1030, UserData.userinfo.host.name, "Helvetica", 28, ccp(0, -40))
  lb:setColor(ccc3(0, 203, 93))
  --print("###3") 
  MainScene.initBuildingLevelLabel()  
  --print("###4") 
  --指挥部
  MainScene.addBuildAction(NodeID.ZhiHuiBu, "jzn1001.plist", "jzn1001_1_1")
  --军校 
  MainScene.addBuildAction(NodeID.JunXiao, "jzn1002.plist", "jzn1002_1_1")
  --科学院
  MainScene.addBuildAction(NodeID.KeXueYuan, "jzn1003.plist", "jzn1003_1_1")
  MainScene.addBuildAction(NodeID.KeXueYuan, "jzn1003.plist", "jzn1003_1_2")
  MainScene.addBuildAction(NodeID.KeXueYuan, "jzn1003.plist", "jzn1003_1_3")
  MainScene.addBuildAction(NodeID.KeXueYuan, "jzn1003.plist", "jzn1003_1_4")
  
  --竞技场 
  MainScene.addBuildAction(NodeID.JinJiChang, "jzn1008.plist", "jzn1008_1_1")
  MainScene.addBuildAction(NodeID.JinJiChang, "jzn1008.plist", "jzn1008_1_2")
  MainScene.addBuildAction(NodeID.JinJiChang, "jzn1008.plist", "jzn1008_1_3")
  MainScene.addBuildAction(NodeID.JinJiChang, "jzn1008.plist", "jzn1008_1_4")
  MainScene.addBuildAction(NodeID.JinJiChang, "jzn1008.plist", "jzn1008_1_5")
  
  --战俘营 
  MainScene.addBuildAction(NodeID.ZhanFuYing, "jzn1004.plist", "jzn1004_1_1")
  
  --训练营
  MainScene.addBuildAction(NodeID.XunLianYing, "jzn1005.plist", "jzn1005_1_1")
  MainScene.addBuildAction(NodeID.XunLianYing, "jzn1005.plist", "jzn1005_1_2")
  MainScene.addBuildAction(NodeID.XunLianYing, "jzn1005.plist", "jzn1005_1_3")

  MainScene.setState()
  
  --RenWuGuide.nextStep()
  --ZhuangBeiGuide.nextStep()
  --XunLianYingGuide.nextStep()
  KeXueYuanGuide.nextStep()
  --JunXiaoGuide.nextStep()
  --ZhiHuiBuGuide.nextStep()
  --MainScene.addMask(1001)
end
MainScene.setBuildingVisible = function()
  local baseLevel = UserData.userinfo.host.cities2["1001"].l 
  for k, v in pairs(UserData.config.models.Building2) do
    local b = MainScene.getBuilding(v.id)
    if b~=nil then
    --if true then
      --b = TypeCast(b, "CCButton")
      --if baseLevel<v.startlevel then
      --if UserData.userinfo.host.cities2[tostring(v.id)]==nil then
      if false then
        --b:setEnabled(false)
        setTouchEnabledAll(b, false)
        b:setVisible(false)
      else
        --b:setEnabled(true)
        setTouchEnabledAll(b, true)
        b:setVisible(true)
      end
    end
  end
end
function onZhiHuiBu()
  MainScene.scene:addChild(ZhiHuiBuScene:getNode().node)
  setTouchEnabledAll(MainScene.node, false)
  --local sc = CCScene:create() 
  --local nd = CCBReader:load("ZhiHuiBu.ccbi")
  --print("onZhiHuiBu", sc, nd)
  --sc:addChild(nd)
  --CCDirector:sharedDirector():replaceScene(CCTransitionSlideInL:create(1,sc))
end

function onJunXieKu()
  --CCDirector:sharedDirector():replaceScene(CCTransitionSlideInL:create(1,ZhuangBeiScene.getScene()))
  MainScene.scene:addChild(ZhuangBeiScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end

function onClose(node)
  print("onClose", node)
  node:getParent():getParent():removeChild(node:getParent(), true)
  MainScene.setState()
  setTouchEnabledAll(MainScene.node, true)
  if MainScene.currentWnd~=nil then
    MainScene.currentWnd.instance = nil
  end
end

function onJingJiChang()
  MainScene.scene:addChild(JingJiChangScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
  --NetworkRequest.jingJiChang()
end
function onJunXiao()
  MainScene.scene:addChild(JunXiaoScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onYuanZhen()
  MainScene.scene:addChild(YuanZhenScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onZhanDou()
  --CCDirector:sharedDirector():replaceScene(CCTransitionSlideInL:create(1,ZhanDouScene.getScene()))
  setTouchEnabledAll(MainScene.node, false)
  LoadScene:showLoadingScene()
  MainScene.scene:runAction(ActionUtil.createSeqAction({CCDelayTime:create(0.001), CCCallFuncN:create(onZhanDouLoadAction)}))
end
function onZhanDouLoadAction()
  MainScene.scene:addChild(ZhanDouScene.getNode().node)
  LoadScene:removeLoadingScene()
end

function onXunLianYing()
  MainScene.scene:addChild(XunLianYingScene:getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onJunYing()
  MainScene.scene:addChild(JunYingScene:getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onYinHang()
  MainScene.scene:addChild(YinHangScene:getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onKeXueYuan(node)
  --print("onKeXueYuan", node, MainScene.scene, MainScene.node:getParent())
  --CCDirector:sharedDirector():replaceScene(CCTransitionSlideInL:create(1,KeXueYuanScene.getScene()))
  --local kxy = CCSprite:create("bb1.png") 
  --kxy:setScale(0.5)
  --MainScene.node:getParent():addChild(kxy)
  --print("onKeXueYuan", MainScene.node)
  --MainScene.node:addChild(kxy)
  local kxy = KeXueYuanScene.getNode()
  MainScene.scene:addChild(kxy.node)
  setTouchEnabledAll(MainScene.node, false)
  --local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  --scroll:setVisible(false)
end
function onZhanFuYing(node)
  MainScene.scene:addChild(ZhanFuYingScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onRenWu(node)
  MainScene.scene:addChild(RenWuScene.getNode().node)
  print("onRenWu -----")
  setTouchEnabledAll(MainScene.node, false)
end
function onRenWuDaily(node)
  MainScene.scene:addChild(RenWuDailyScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onJiuGuan(node)
  MainScene.scene:addChild(JiuGuanScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onShouXun(node)
  MainScene.scene:addChild(ShouXunScene1.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onFriend(node)
  MainScene.scene:addChild(FriendScene.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onShop(node)
  MainScene.scene:addChild(ShopScene1.getNode().node)
  setTouchEnabledAll(MainScene.node, false)
end
MainScene.enableTouch = function(enable)
  setTouchEnabledAll(MainScene.node, enable)
  --local scroll = MainScene.node:getChildByTag(NodeID.ScrollView)
  --scroll = TypeCast(scroll, "CCScrollView")
  --setTouchEnabledAll(scroll:getContainer(), enable)
end
function onAddPowerButton(node)
  MainScene.scene:addChild(AddPowerCashScene.createAddPowerDialog().node)
  setTouchEnabledAll(MainScene.node, false)
end
function onAddCashButton(node)
  MainScene.scene:addChild(AddPowerCashScene.createAddCashDialog().node)
  setTouchEnabledAll(MainScene.node, false)
end

